package com.acerola.rocketmqspringboot.controller;

import com.acerola.rocketmqspringboot.pojo.User;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: RocketMQSpringboot
 * @description:
 * @author: Acerola
 * @create: 2022-10-02 10:22
 **/
@RestController
public class DemoProducers {
    @Autowired
    private RocketMQTemplate template;

    @RequestMapping("/producer")
    public String producersMessage() {
        User user = new User("sharfine", "123456789");
        template.convertAndSend("demo-topic", user);
        //同步消息
        template.syncSend("demo-topic",user);
        //异步消息
        template.asyncSend("demo-topic", user, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable);
            }
        });
        //单向消息
        template.sendOneWay("demo-topic",user);
        //延时消息
        template.syncSend("topic9", MessageBuilder.withPayload("test delay").build(),2000,2);
        //批量消息
        List<Message> msgList = new ArrayList<>();
        msgList.add(new Message("topic6", "tag1", "msg1".getBytes()));
        msgList.add(new Message("topic6", "tag1", "msg2".getBytes()));
        msgList.add(new Message("topic6", "tag1", "msg3".getBytes()));
        template.syncSend("topic8",msgList,1000);

        return JSON.toJSONString(user);
    }
}
